package com.demo.java.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.*;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;


@Slf4j
public class RedissonClientTest {
    public static void main(String[] args) throws InterruptedException {
        RedissonClient client = createSingleClient();

        RList<String> list = client.getList("test");
        list.add("aa");

        list.deleteAsync();

        client.shutdown();
    }

    public static RedissonClient createSingleClient() {
        String hosts = "10.97.8.212:6379";
        String password = null;

        Config config = new Config();
        final SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://" + hosts);

        if (Objects.nonNull(password)) {
            singleServerConfig.setPassword(password);
        }

        return Redisson.create(config);
    }

    public static RedissonClient createClusterClient() {
        String hosts = "10.97.8.212:6379,10.97.8.213:6379";
        String password = null;

        String[] addressArr = Arrays.asList(hosts.split(",")).stream().map(x -> "rediss://" + x).collect(Collectors.toList()).toArray(new String[0]);

        Config config = new Config();
        ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(addressArr);

        if (Objects.nonNull(password)) {
            clusterServersConfig.setPassword(password);
        }

        return Redisson.create(config);
    }
}
